package cn.gpdi.framework.sys;

import cn.gpdi.framework.pojo.FwLoginException;
import org.apache.log4j.Logger;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

//全局异常处理器
public class AjaxExceptionResolver implements HandlerExceptionResolver {
    Logger logger = Logger.getLogger(AjaxExceptionResolver.class);

    //系统抛出的异常
    @Override
    public ModelAndView resolveException(HttpServletRequest request,
                                         HttpServletResponse response, Object handler, Exception ex) {
        ModelAndView mv = new ModelAndView();
        logger.error(ex.getMessage(), ex);   //保存日志
        StringBuffer content = new StringBuffer();
        if (ex instanceof AjaxException) {
            //如果是自定义的异常。。
        } else {
            ex.printStackTrace();
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            ex.printStackTrace(pw);
            Map rm=new HashMap();
            if (ex instanceof FwLoginException){    //登陆异常
                rm.put("code","-99");
            }else{
                rm.put("code","-1");
            }
            rm.put("message", ex.getMessage());
            rm.put("detail",sw.toString());
            MappingJackson2JsonView view = new MappingJackson2JsonView();
            view.setAttributesMap(rm);
            mv.setView(view);
        }
        response.setCharacterEncoding("UTF-8"); //避免乱码
        response.setHeader("Cache-Control", "no-cache, must-revalidate");
        return mv;
    }

}